package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IRecordBorrowService;
import com.ruoyi.system.service.IRecordManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 借阅管理Service业务层处理
 *
 * @author admin
 * @date 2022-03-10
 */
@Service
public class RecordBorrowServiceImpl implements IRecordBorrowService {
    @Autowired
    private RecordBorrowMapper recordBorrowMapper;
    @Autowired
    private RecordBorcartMapper recordBorcartMapper;
    @Autowired
    private RecordManageMapper recordManageMapper;
    @Autowired
    private IRecordManageService iRecordManageService;

    /**
     * 查询借阅管理
     *
     * @param borrowId 借阅管理主键
     * @return 借阅管理
     */
    @Override
    public RecordBorrow selectRecordBorrowByBorrowId(Long borrowId) {
        return recordBorrowMapper.selectRecordBorrowByBorrowId(borrowId);
    }

    /**
     * 查询借阅管理列表
     *
     * @param recordBorrow 借阅管理
     * @return 借阅管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RecordBorrow> selectRecordBorrowList(RecordBorrow recordBorrow) {
        return recordBorrowMapper.selectRecordBorrowList(recordBorrow);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public int selectRecordBorrowGetCount(RecordBorrow recordBorrow) {
        return recordBorrowMapper.selectRecordBorrowGetCount(recordBorrow);
    }

    /**
     * 新增借阅管理
     *
     * @param recordBorrow 借阅管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRecordBorrow(RecordBorrow recordBorrow) {
        // 1,遍历案卷信息
        // 2,赋值借阅信息内容
        // 3,逐条插入借阅信息
        // 4,若案卷已被实体借出，不可再借阅
        // 5,添加借阅信息成功,则删除购物车信息
        // 6,更新案卷实体借阅状态为1，
        Object savePoint = null;
        for (RecordBorcart cart : recordBorrow.getBorcartList()) {
            // 设置回滚点
            savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
            recordBorrow.setCreateTime(DateUtils.getNowDate());
            recordBorrow.setApplyTime(DateUtils.getNowDate());
            recordBorrow.setUserId(cart.getUserId());
            recordBorrow.setArchivesId(cart.getArchivesId());
            recordBorrow.setTbName(cart.getTbName());
            recordBorrow.setTypeName(cart.getTypeName());
            recordBorrow.setTbType(cart.getTbType());
            recordBorrow.setFileTitle(cart.getFileTitle());
            recordBorrow.setDocNum(cart.getDocNum());
            recordBorrow.setFullAnces(cart.getFullAnces());
            recordBorrow.setTypeId(cart.getTypeId());
            borrow(cart, savePoint, recordBorrow);

        }
        return 1;
    }

    private void borrow(RecordBorcart cart, Object savePoint, RecordBorrow recordBorrow) {
        //获取案卷信息
        Map<String, Object> map = recordManageMapper.selectRecordManageById(cart.getArchivesId(), cart.getTbName());
        // 实体借阅申请 && 案卷已被借出 ， 已经不限制实体借阅
//        if ("1".equals(recordBorrow.getOffline()) && map != null && "1".equals(map.get("borwStatus").toString())) {
//            //手工回滚异常
//            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
//            throw new ServiceException("题名" + map.get("fileTile").toString() + "已被借出，请重新选择！");
//        }
        // 添加借阅信息
        int resBor = recordBorrowMapper.insertRecordBorrow(recordBorrow);
        // 删除借阅车
        int resCart = recordBorcartMapper.deleteRecordBorcartByCartId(cart.getCartId());
        // 如果是实体借阅，则更新案卷实体借阅状态为1, 已借出状态
        if ("1".equals(recordBorrow.getOffline())) {
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", recordBorrow.getArchivesId());
            mapNew.put("borwStatus", "1");
            mapNew.put("tbName", cart.getTbName());
            int resArch = iRecordManageService.updateRecordManage(mapNew);
            if (resArch != 1) {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("操作失败！数据更新条数为0");
            }
        }
        if (resBor != 1 || resCart != 1) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException("操作失败！数据更新条数为0");
        }
    }

    /**
     * 修改借阅管理
     *
     * @param recordBorrow 借阅管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRecordBorrow(RecordBorrow recordBorrow) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            recordBorrow.setUpdateTime(DateUtils.getNowDate());
            recordBorrowMapper.updateRecordBorrow(recordBorrow);
            // 如果是实体借阅，则更新案卷实体借阅状态为0,未借出状态
            if ("1".equals(recordBorrow.getOffline())) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", recordBorrow.getArchivesId());
                map.put("borwStatus", "1");
                map.put("tbName", recordBorrow.getTbName());
                iRecordManageService.updateRecordManage(map);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 批量删除借阅管理
     *
     * @param borrowIds 需要删除的借阅管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordBorrowByBorrowIds(Long[] borrowIds) {
        return recordBorrowMapper.deleteRecordBorrowByBorrowIds(borrowIds);
    }

    /**
     * 删除借阅管理信息
     *
     * @param borrowId 借阅管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordBorrowByBorrowId(Long borrowId) {
        return recordBorrowMapper.deleteRecordBorrowByBorrowId(borrowId);
    }

    @Override
    @Transactional
    public int updateApprove(Long[] borrowIds) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < borrowIds.length; i++) {
            RecordBorrow recordBorrow = new RecordBorrow();
            recordBorrow.setBorrowId(borrowIds[i]);
            recordBorrow.setAuditUser(SecurityUtils.getUsername());
            recordBorrow.setAuditTime(DateUtils.getNowDate()); // 审批时间
            recordBorrow.setAuditState("2"); //申请状态字段,2：通过
            RecordBorrow recordBorrowOld = recordBorrowMapper.selectRecordBorrowByBorrowId(borrowIds[i]);
            if ("1".equals(recordBorrowOld.getAuditState())) { // 申请中状态，可审批
                int res = recordBorrowMapper.updateRecordBorrow(recordBorrow);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateReject(Long[] borrowIds) {
        // 1.更新借阅车状态为3，审批拒绝
        // 2.更新案卷信息状态为0，未借出

        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < borrowIds.length; i++) {
            RecordBorrow recordBorrow = new RecordBorrow();
            recordBorrow.setBorrowId(borrowIds[i]);
            recordBorrow.setAuditUser(SecurityUtils.getUsername());
            recordBorrow.setAuditTime(DateUtils.getNowDate()); // 审批时间
            recordBorrow.setAuditState("3"); //申请状态字段，3：拒绝
            RecordBorrow recordBorrowOld = recordBorrowMapper.selectRecordBorrowByBorrowId(borrowIds[i]);
            if ("1".equals(recordBorrowOld.getAuditState())) { // 申请中状态，可审批
                int res = recordBorrowMapper.updateRecordBorrow(recordBorrow);
                // 如果是实体借阅，则更新案卷实体借阅状态为0,未借出状态
                if ("1".equals(recordBorrowOld.getOffline())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", recordBorrowOld.getArchivesId());
                    map.put("borwStatus", "0");
                    map.put("tbName", recordBorrowOld.getTbName());
                    int resArch = iRecordManageService.updateRecordManage(map);
                    if (resArch != 1) { // 更新条数为0
                        //手工回滚异常
                        TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                        throw new ServiceException("操作失败！数据更新条数为0");
                    }
                }
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateGiveBack(Long[] borrowIds) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < borrowIds.length; i++) {
            // 获取当前借阅记录
            RecordBorrow recordBorrowOld = recordBorrowMapper.selectRecordBorrowByBorrowId(borrowIds[i]);
            // 审核通过、未归还状态、且是实体借阅，可归还
            if ("2".equals(recordBorrowOld.getAuditState()) && "0".equals(recordBorrowOld.getStatus()) && "1".equals(recordBorrowOld.getOffline())) {
                // 借阅记录更新
                RecordBorrow recordBorrow = new RecordBorrow();
                recordBorrow.setBorrowId(borrowIds[i]);
                recordBorrow.setBackTime(DateUtils.getNowDate()); // 归还时间
                recordBorrow.setStatus("1"); // 归还状态,1：已归还
                int resBro = recordBorrowMapper.updateRecordBorrow(recordBorrow);
                //则更新案卷实体借阅状态为0,未借出状态
                Map<String, Object> map = new HashMap<>();
                map.put("id", recordBorrowOld.getArchivesId());
                map.put("borwStatus", "0");
                map.put("tbName", recordBorrowOld.getTbName());
                int resArch = iRecordManageService.updateRecordManage(map);
                if (resBro != 1 || resArch != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作实体借阅未归还的记录");
            }
        }
        return 1;
    }
}
